package db

import (
	"encoding/base64"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gotest/src/common"
	"log"
)

var Db *gorm.DB

func init() {
	var err error
	data := LoadConfig()
	if data == nil {
		log.Println("加载数据库配置信息异常:")
		return
	}
	//解密用户名和密码
	bytesPass, err := base64.StdEncoding.DecodeString(data.Datasource.Username)
	if err != nil {
		fmt.Println(err)
		return
	}
	decUserName, _ := common.AesDecrypt(bytesPass, common.Key)
	Db, err = gorm.Open(data.Datasource.Dialect, string(decUserName)+"@tcp("+data.Datasource.Url+")/go")
	if err != nil {
		log.Panicln("err:", err.Error())
	}
}

func closeDb() {
	if Db != nil {
		Db.Close()
	}
}
